package org.shangda.wechat.pet.util;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * 图片合成工具类
 */
@Slf4j
public class ImageMergingUtil {
    private Font font = new Font("微软雅黑", Font.PLAIN, 46); // 添加字体的属性设置

    private Graphics2D g = null;

    private int fontsize = 0;

    private int x = 0;

    private int y = 0;

    /**
     * 将本地图片导入到内存缓冲区
     * @param imgPath
     * @return
     */
    public BufferedImage loadImageLocal(String imgPath) {
        try {
            return ImageIO.read(new File(imgPath));
        } catch (IOException e) {
            log.error("loadImageLocal exception:", e);
        }
        return null;
    }

    /**
     * 将网络图片导入到内存缓冲区
     * @param imageUrl 网路图片地址
     * @return
     */
    public BufferedImage loadImageUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            return ImageIO.read(url);
        } catch (IOException e) {
            log.error("loadImageUrl exception", e);
        }
        return null;
    }

    /**
     * 将新图片保存到磁盘
     * @param newImagePath 新图片保存磁盘路径
     * @param img 新图片对象
     */
    public void writeImageLocal(String newImagePath, BufferedImage img) {
        if (newImagePath != null && img != null) {
            try {
                File outputfile = new File(newImagePath);
                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
                log.error("writeImageLocal exception", e);
            }
        }
    }

    /**
     * 设定文字的字体等
     */
    public void setFont(String fontStyle, int fontSize) {
        this.fontsize = fontSize;
        this.font = new Font(fontStyle, Font.PLAIN, fontSize);
    }

    /**
     * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
     */
    public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y) {

        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(new Color(255, 255, 255, 0));
            g.setColor(Color.WHITE);//设置字体颜色
            g.setFont(new Font("微软雅黑", Font.PLAIN, 46));
            if (this.font != null)
                g.setFont(this.font);
            // 验证输出位置的纵坐标和横坐标  
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (content != null) {
                g.drawString(content.toString(), this.x, this.y);
            }
            g.dispose();
        } catch (Exception e) {
            log.error("modifyImage exception", e);
        }

        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区（输出多个文本段） xory：true表示将内容在一行中输出；false表示将内容多行输出
     */
    public BufferedImage modifyImage(BufferedImage img, Object[] contentArr, int x, int y,
                                     boolean xory) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.RED);
            if (this.font != null)
                g.setFont(this.font);
            // 验证输出位置的纵坐标和横坐标  
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (contentArr != null) {
                int arrlen = contentArr.length;
                if (xory) {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.x += contentArr[i].toString().length() * this.fontsize / 2 + 5;// 重新计算文本输出位置  
                    }
                } else {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.y += this.fontsize + 2;// 重新计算文本输出位置  
                    }
                }
            }
            g.dispose();
        } catch (Exception e) {
            log.error("modifyImage exception:", e);
        }

        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
     * @param img
     * @return
     */
    public BufferedImage modifyImageYe(BufferedImage img) {

        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.blue);//设置字体颜色  
            if (this.font != null) {
                g.setFont(this.font);
            }
            //g.drawString("www.hi.baidu.com?xia_mingjian", w - 85, h - 5);
            g.dispose();
        } catch (Exception e) {
            log.error("modifyImageYe");
        }

        return img;
    }

    /**
     * 将图片合并在一起
     * @param upImage 被合成图片
     * @param backgroundImg 背景图片
     * @param width 被合成图片在背景图上 x坐标
     * @param height 被合成图片在背景图上 y坐标
     * @return
     */
    public BufferedImage modifyImagetogeter(BufferedImage upImage, BufferedImage backgroundImg, int width, int height) {
        try {
            int w = upImage.getWidth();
            int h = upImage.getHeight();
            g = backgroundImg.createGraphics();
            g.drawImage(upImage, width, height, w, h, null);
            g.dispose();
        } catch (Exception e) {
            log.error("modifyImagetogeter exception", e);
        }
        return backgroundImg;
    }

    /**
     * BufferedImage拷贝
     * @param source
     * @return
     */
    public BufferedImage copyImage(BufferedImage source) {
        BufferedImage copyBufferedImage = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
        Graphics g = copyBufferedImage.getGraphics();
        g.drawImage(source, 0, 0, null);
        g.dispose();
        return copyBufferedImage;
    }

    /**
     * 批量生成照片时，如果背景图片是一个时，对其进行拷贝在修改。
     * @param pic
     * @param unitName
     * @param qRCode
     * @param backgroundImage
     * @param fontMetrics
     * @return
     */
    public BufferedImage qRCodeGeneration(ImageMergingUtil pic, String unitName, BufferedImage qRCode, BufferedImage backgroundImage, FontMetrics fontMetrics) {
        int strWidth = fontMetrics.stringWidth(unitName);

        BufferedImage copyBufferedImage = copyImage(backgroundImage);

        BufferedImage backgroundAndName = pic.modifyImage(copyBufferedImage, unitName, (1400 - strWidth) / 2, 1050);


        BufferedImage bufferedImage = pic.modifyImagetogeter(qRCode, backgroundAndName, 342, 218);

        return bufferedImage;
    }


    public static void main(String[] args) {
        ImageMergingUtil tt = new ImageMergingUtil();
        BufferedImage backgroundImg = tt.loadImageLocal("./data/imgs/11.png");
        BufferedImage upImg = tt.loadImageLocal("./data/imgs/22.png");
        //往图片上写文件
        tt.writeImageLocal("./data/imgs/33.jpg", tt.modifyImagetogeter(upImg, backgroundImg, 100, 10));

        //将多张图片合在一起  
        System.out.println("success");
    }

}